﻿using System.Drawing;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Xml.Linq;
using AutoMapper;
using DataManageSystem.Common;
using DataManageSystem.Data;
using DataManageSystem.Exceptions;
using DataManageSystem.Models;
using DataManageSystem.Models.Dto;
using DataManageSystem.Models.LimsModels;
using DataManageSystem.Utils;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;

namespace DataManageSystem.Services
{
    public class UserServices
    {
        private readonly ApplicationDbContext _context;
        private readonly IConfiguration _config;
        private readonly IMapper _mapper;
        private readonly HttpContextAccessor httpContextAccessor;
        private readonly IServiceScopeFactory _scopeFactory;

        public UserServices(
            ApplicationDbContext context,
            IConfiguration config,
            IMapper mapper,
            IServiceScopeFactory scopeFactory
        )
        {
            _context = context;
            _config = config;
            _mapper = mapper;
            _scopeFactory = scopeFactory;

        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        /// <exception cref="ServiceException"></exception>
        public User login(User user)
        {
            var dbUser = _context.User.Where(u => u.Username == user.Username).FirstOrDefault();
            if (dbUser == null)
            {
                throw new ServiceException("用户名或密码错误");
            }
            if (!user.Password.Equals(dbUser.Password))
            {
                throw new ServiceException("用户名或密码错误");
            }
            string token = GenerateJwtToken(dbUser);
            dbUser.Token = token;
            return dbUser;
        }

        /// <summary>
        /// 生成JWT Token
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        private string GenerateJwtToken(User user)
        {
            var key = Encoding.ASCII.GetBytes(_config["Jwt:Key"]);
            var tokenHandler = new JwtSecurityTokenHandler();
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(
                    new[]
                    {
                        new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                        new Claim(ClaimTypes.Name, user.Username),
                    }
                ),
                Expires = DateTime.UtcNow.AddDays(7), // 7 天有效期
                SigningCredentials = new SigningCredentials(
                    new SymmetricSecurityKey(key),
                    SecurityAlgorithms.HmacSha256Signature
                ),
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(token);
        }

        /// <summary>
        /// 查询用户
        /// </summary>
        /// <param name="page"></param>
        /// <param name="size"></param>
        /// <param name="username"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public Result selectByPage(int page, int size, string username, string name)
        {
            var query = _context.User.AsQueryable();
            if (!string.IsNullOrEmpty(username))
            {
                query = query.Where(u => u.Username.Contains(username));
            }
            if (!string.IsNullOrEmpty(name))
            {
                query = query.Where(u => u.Name.Contains(name));
            }

            int total = query.Count(); // 获取总记录数

            var users = query
                .OrderByDescending(u => u.Id)
                .Skip((page - 1) * size)
                .Take(size)
                .ToList();
            return Result.Success(users, total);
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="user"></param>
        /// <exception cref="ServiceException"></exception>
        public void add(User user)
        {
            if (string.IsNullOrEmpty(user.Username))
            {
                throw new ServiceException("用户名");
            }

            //检查用户名是否存在
            var existingUser = _context.User.FirstOrDefault(u => u.Username == user.Username);

            if (existingUser != null)
            {
                throw new ServiceException("用户名已存在");
            }

            user.Password = user.Password ?? "123456"; // 设置默认密码
            user.Address = user.Address ?? "江苏省南京市建邺区创新广场A座"; // 设置默认地址
            // 添加用户到数据库
            _context.User.Add(user);
            _context.SaveChanges();
        }

        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <param name="userDto"></param>
        /// <exception cref="ServiceException"></exception>
        public void update(UserDto userDto)
        {
            if (userDto == null || userDto.Id <= 0)
            {
                throw new ServiceException("无效的用户信息");
            }
            var existUser = _context.User.FirstOrDefault(u => u.Id == userDto.Id);
            if (existUser == null)
            {
                throw new ServiceException("用户不存在");
            }
            //更新用户信息
            _mapper.Map(userDto, existUser); // 自动映射 DTO 到实体
            _context.User.Update(existUser);
            _context.SaveChanges();
        }

        /// <summary>
        /// 根据用户ID获取用户信息
        /// </summary>
        /// <param name="parsedUserId"></param>
        /// <returns></returns>
        public User? getUserById(int parsedUserId)
        {
            return _context.User.FirstOrDefault(u => u.Id == parsedUserId);
        }

        /// <summary>
        /// 根据用户ID删除用户
        /// </summary>
        /// <param name="id"></param>
        /// <exception cref="ServiceException"></exception>
        public void delete(int id)
        {
            var user = _context.User.FirstOrDefault(u => u.Id == id);
            if (user != null)
            {
                _context.User.Remove(user);
                _context.SaveChanges();
            }
            else
            {
                throw new ServiceException("用户不存在");
            }
        }

        public string Migration()
        {
            using (var scope = _scopeFactory.CreateScope())
            {
                var dbContext = scope.ServiceProvider.GetRequiredService<DeviceDbContext>();

                // 获取已存在的 userId（去重）
                var existingUserAccounts = dbContext
                    .TAccounts.Select(m => m.UserId)
                    .ToHashSet();

                // 过滤未迁移的设备
                var users = _context
                    .User.Where(m => !existingUserAccounts.Contains(m.Username))
                    .ToList();

                if (!users.Any())
                    return "没有需要迁移的人员信息"; // 如果没有新数据，直接返回

                // 准备迁移数据
                var accounts = users
                    .Select(m => new TAccount
                    {
                        Guid = Guid.NewGuid().ToString(),
                        UserId = m.Username,
                        UserName = m.Name,
                        Password = "dd4b21e9ef71e1291183a46b913ae6f2",
                        EmailAddress = m.Email,
                        RoleId = "",
                        Description = "",
                        InitPwd = false,
                        ExtraInfo = null,
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now,
                        CreateUser = "lkc",
                        UpdateUser = "lkc",
                        Valid = true,
                        DeptGuid = null,
                        Phone = m.Phone,
                        Status = 1,
                        ReportId = null,
                        Type = null,
                        Openid = null,
                        DoorAccessPersonId = null
                    })
                    .ToList();

                // 批量写入数据库
                dbContext.TAccounts.AddRange(accounts);
                dbContext.SaveChanges();
                return "迁移成功";
            }
        }

        public object selectByName(string userName)
        {
            var query = _context.User.AsQueryable();
            if (!string.IsNullOrEmpty(userName))
            {
                query = query.Where(u => u.Username.Contains(userName));
            }
            int total = query.Count(); // 获取总记录数

            var users = query
                .OrderByDescending(u => u.Id)
                .ToList();
            return Result.Success(users, total);
        }
    }
}
